package org.dromara.system.controller;

import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.system.domain.bo.SkyBagBo;
import org.dromara.system.domain.bo.SkyRelationshipBo;
import org.dromara.system.domain.vo.SkyBagVo;
import org.dromara.system.domain.vo.SkyRelationshipVo;
import org.dromara.system.domain.vo.WbCandidateListRiskVo;
import org.dromara.system.listener.WbCandidateListListener;
import org.dromara.system.service.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.WbCandidateListVo;
import org.dromara.system.domain.bo.WbCandidateListBo;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 中标候选人详情
 *
 * @author Lion Li
 * @date 2024-05-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/candidateList")
public class WbCandidateListController extends BaseController {

    private final IWbCandidateListService wbCandidateListService;
    private final IWbCompanyInfoService wbCompanyInfoService;
    private final IWbCandidateService candidateService;
    private final IWbCandidateInfoService candidateInfoService;

    /**
     * 查询中标候选人详情列表
     */
    @SaCheckPermission("system:candidateList:list")
    @GetMapping("/list")
    public TableDataInfo<WbCandidateListVo> list(WbCandidateListBo bo, PageQuery pageQuery) {
        return wbCandidateListService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出采购分包列表模板
     */
    @SaCheckPermission("system:candidateList:export")
    @Log(title = "中标分包内容", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        List<WbCandidateListVo> list = new ArrayList<>();
        WbCandidateListVo wbCandidateListVo = new WbCandidateListVo();
        wbCandidateListVo.setSubStandardId("0424C1-9200000-XXXX");
        wbCandidateListVo.setSubStandardName("分标名");
        wbCandidateListVo.setBagNo("包号");
        wbCandidateListVo.setBagName("包名");
        wbCandidateListVo.setCandidate("推荐中标候选人");
        list.add(wbCandidateListVo);
        ExcelUtil.exportExcel(list, "中标分包内容", WbCandidateListVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file 导入文件
     */
    @Log(title = "采购分包内容", businessType = BusinessType.IMPORT)
    @SaCheckPermission("system:candidateList:add")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, Long candidateId, String status) throws Exception {
        if(StringUtils.isNotEmpty(status) && "1".equals(status)) {
            //删除原分包数据
            removeByCandidateId(candidateId, "0");
        }

        return R.ok(importFile(file, candidateId));
    }

    /**
     * 上传文件
     * @param file 文件
     * @param candidateId 标ID
     * @return 回执结果
     */
    private String importFile(MultipartFile file, Long candidateId) throws Exception {
        //导入数据，关联到项目信息candidateId
        //此方法将包数据存储到数据库
        ExcelResult<WbCandidateListVo> result = ExcelUtil.importExcel(file.getInputStream(), WbCandidateListVo.class,new WbCandidateListListener(candidateId));
        //导入回执
        String analysis = result.getAnalysis();

        candidateService.startAnalysis(candidateId);
        candidateInfoService.updateStatus(candidateId, "1");
        return analysis;
    }

    /**
     * 导出中标候选人详情列表
     */
    @SaCheckPermission("system:candidateList:export")
    @Log(title = "中标候选人详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WbCandidateListBo bo, HttpServletResponse response) {
        List<WbCandidateListRiskVo> list = candidateService.queryVendorList(bo);
        ExcelUtil.exportExcel(list, "项目供应商详情", WbCandidateListRiskVo.class, response);
    }

    /**
     * 导出天眼查股权关系列表
     */
    @SaCheckPermission("system:relationship:export")
    @Log(title = "天眼查股权关系", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRelationship")
    public void export(SkyRelationshipBo bo, HttpServletResponse response) {
        List<SkyRelationshipVo> list =   candidateService.queryRelationship(bo);
        ExcelUtil.exportExcel(list, "项目股权关系", SkyRelationshipVo.class, response);
    }

    /**
     * 获取中标候选人详情详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:candidateList:query")
    @GetMapping("/{id}")
    public R<WbCandidateListVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(wbCandidateListService.queryById(id));
    }

    /**
     * 新增中标候选人详情
     */
    @SaCheckPermission("system:candidateList:add")
    @Log(title = "中标候选人详情", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WbCandidateListBo bo) {
        wbCompanyInfoService.handleName(bo.getCandidate());
        return toAjax(wbCandidateListService.insertByBo(bo));
    }

    /**
     * 修改中标候选人详情
     */
    @SaCheckPermission("system:candidateList:edit")
    @Log(title = "中标候选人详情", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody WbCandidateListBo bo) {
        wbCompanyInfoService.handleName(bo.getCandidate());
        return toAjax(wbCandidateListService.updateByBo(bo));
    }

    /**
     * 删除中标候选人详情
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:candidateList:remove")
    @Log(title = "中标候选人详情", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(wbCandidateListService.deleteWithValidByIds(List.of(ids), true));
    }

    private void removeByCandidateId(Long candidateId, String status) {
        wbCandidateListService.removeByCandidateId(candidateId);
        candidateInfoService.updateStatus(candidateId, status);
    }

    /**
     * 查询分包详情列表
     */
    @SaCheckPermission("system:candidateList:list")
    @GetMapping("/listCandidate")
    public TableDataInfo listCandidate(WbCandidateListBo bo, PageQuery pageQuery) {
        return wbCandidateListService.queryCandidatePageList(bo, pageQuery);
    }

    /**
     * 查询企业股权架构
     * @param bo 条件
     */
    @SaCheckPermission("system:candidateList:query")
    @GetMapping("/queryRelationship")
    public R<List<SkyBagVo>> queryNodeRelationship(SkyBagBo bo) {
        //处理企业股权架构
        return R.ok(candidateService.queryShareholding(bo));
    }

    @SaCheckPermission("system:candidateList:query")
    @GetMapping("/testAnalyse")
    public R<String> testAnalyse() {
        candidateService.startAnalysis(1837049424534437890L);
        return R.ok();
    }
}

